<template>
  <div class="geolocation">
    <div>latitude：<span>{{latitude}}</span></div>
    <div>longitude：<span>{{longitude}}</span></div>
    <div>addresses：<span>{{country}}{{addresses}}</span></div>
    <div>
      <button @click.stop="WatchLocation">{{!wwid?'打开':'关闭'}}监听位置信息</button>
    </div>
  </div>
</template>

<script>
  export default {
    name: "geolocation",
    data() {
      return {
        wwid: null,
        latitude: "",
        longitude: "",
        country: "",
        addresses: "",
      }
    },
    mounted() {
      this.geolocation();
    },
    methods: {
      geolocation() {
        const that = this;
        plus.geolocation.getCurrentPosition(function (res) {
          that.latitude = res.coords.latitude;
          that.longitude = res.coords.longitude;
          that.country = res.address.country;
          that.addresses = res.addresses;
        }, function (e) {
          mui.alert('Geolocation error: ' + e.message, "", "", "", "div");
        }, {provider: 'amap'});
      },
      WatchLocation() {
        var that = this;
        if(!that.wwid){
          mui.confirm("确定打开监听当前位置信息吗？", "提示", ['否', '是'], function (e) {
            if (e.index == 1) {
              that.wwid = plus.geolocation.watchPosition(function (res) {
                that.latitude = res.coords.latitude;
                that.longitude = res.coords.longitude;
                that.country = res.address.country;
                that.addresses = res.addresses;
              }, function (e) {
                console.log('Geolocation error: ' + e.message);
              }, {
                enableHighAccuracy: true,
                maximumAge: 100,
                provider: 'amap'
              });
            }
          }, 'div');
        }else{
          mui.confirm("确定关闭监听当前位置信息吗？", "提示", ['否', '是'], function (e) {
            if (e.index == 1) {
              plus.geolocation.clearWatch(that.wwid);
              that.wwid = null;
            }
          }, 'div');
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .geolocation {
    width: 100%;
    height: 100%;
    padding: 10px;
    div {
      width: 100%;
      height: 45px;
      font-size: 12px;
      background: white;
      display: flex;
      align-items: center;
      padding-left: 5px;
      margin-bottom: 10px;

      span {
        color: red;
        font-size: 10px;
      }
    }
  }
</style>
